<template>
  <div class="home-container">
    <!-- 顶部导航 -->
    <Header :cart-count="cartCount" @open-cart="showCartDialog = true" />
    
    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 搜索和分类区域 -->
      <div class="search-category-section">
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="搜索商品..."
            prefix-icon="el-icon-search"
            @input="handleSearch"
            clearable
          >
            <template #append>
              <el-button>搜索</el-button>
            </template>
          </el-input>
        </div>

        <div class="categories">
          <el-radio-group v-model="selectedCategory">
            <el-radio-button :label="null">全部</el-radio-button>
            <el-radio-button
              v-for="category in categories"
              :key="category.id"
              :label="category.id"
            >
              {{ category.name }}
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="products-grid">
        <el-card
          v-for="product in filteredProducts"
          :key="product.id"
          class="product-card"
          :body-style="{ padding: '0px' }"
        >
          <img
            :src="product.image"
            :alt="product.name"
            @click="openProductDetail(product.id)"
          >
          <div class="product-info">
            <h3>{{ product.name }}</h3>
            <p class="price">¥{{ product.price }}</p>
            <div class="product-actions">
              <el-button type="warning" @click="addToCart(product)">
                加入购物车
              </el-button>
              <el-button type="danger" @click="buyNow(product)">
                立即购买
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 商品详情弹窗 -->
    <el-dialog
      v-model="showProductDialog"
      title="商品详情"
      width="50%"
      :fullscreen="false"
      :modal="true"
      destroy-on-close
      :close-on-click-modal="false"
      :before-close="handleCloseProductDialog"
    >
      <ProductDetail
        v-if="showProductDialog"
        :product-id="selectedProductId"
        @close="closeProductDialog"
        @add-to-cart="handleAddToCart"
      />
    </el-dialog>

    <!-- 购物车弹窗 -->
    <el-dialog
      v-model="showCartDialog"
      title="购物车"
      width="70%"
      destroy-on-close
      :close-on-click-modal="false"
      :before-close="handleCloseCartDialog"
    >
      <Cart
        v-if="showCartDialog"
        @close="closeCartDialog"
        @view-product="openProductDetail"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import Header from '@/components/Header.vue'
import ProductDetail from '@/views/ProductDetail.vue'
import Cart from '@/views/Cart.vue'

const router = useRouter()
const products = ref([
  // 模拟数据
  {
    id: 1,
    name: "商品1",
    price: 99.99,
    image: "https://via.placeholder.com/200",
    categoryId: 1
  },
  {
    id: 2,
    name: "商品2",
    price: 199.99,
    image: "https://via.placeholder.com/200",
    categoryId: 2
  }
])
const categories = ref([
  { id: 1, name: "分类1" },
  { id: 2, name: "分类2" }
])
const selectedCategory = ref(null)
const searchQuery = ref('')
const cartCount = ref(0)

// TODO: API - 获取商品列表
const getProducts = async () => {
  // const response = await request.get('/api/products')
  // products.value = response.data
}

// TODO: API - 获取分类列表
const getCategories = async () => {
  // const response = await request.get('/api/categories')
  // categories.value = response.data
}

// 筛选商品
const filteredProducts = computed(() => {
  let result = products.value

  if (selectedCategory.value) {
    result = result.filter(p => p.categoryId === selectedCategory.value)
  }

  if (searchQuery.value) {
    result = result.filter(p => 
      p.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  return result
})

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
}

// 搜索处理
const handleSearch = () => {
  // 可以添加防抖处理
}

// 跳转到详情页
const goToDetail = (productId) => {
  router.push(`/product/${productId}`)
}

// TODO: API - 添加到购物车
const addToCart = async (product) => {
  try {
    // await request.post('/api/cart', {
    //   productId: product.id,
    //   quantity: 1
    // })
    alert('添加成功')
    updateCartCount()
  } catch (error) {
    alert('添加失败')
  }
}

// 立即购买
const buyNow = (product) => {
  router.push({
    path: '/cart',
    query: {
      productId: product.id,
      quantity: 1,
      direct: true
    }
  })
}

// TODO: API - 获取购物车数量
const updateCartCount = async () => {
  // const response = await request.get('/api/cart/count')
  // cartCount.value = response.data
}

// 商品详情弹窗相关
const showProductDialog = ref(false)
const selectedProductId = ref(null)

const openProductDetail = (productId) => {
  selectedProductId.value = productId
  showProductDialog.value = true
}

const closeProductDialog = () => {
  showProductDialog.value = false
  selectedProductId.value = null
}

const handleCloseProductDialog = (done) => {
  closeProductDialog()
  done()
}

// 购物车弹窗相关
const showCartDialog = ref(false)

const closeCartDialog = () => {
  showCartDialog.value = false
}

const handleCloseCartDialog = (done) => {
  closeCartDialog()
  done()
}

// 处理商品详情页面添加购物车事件
const handleAddToCart = async (productId, quantity) => {
  await addToCart({ id: productId }, quantity)
}

onMounted(() => {
  getProducts()
  getCategories()
  updateCartCount()
})
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 60px 20px 20px;
}

.search-category-section {
  text-align: center;
  margin-bottom: 30px;
}

.search-box {
  max-width: 500px;
  margin: 0 auto 15px;
}

.categories {
  margin-bottom: 20px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
}

.product-card {
  transition: transform 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-card img {
  width: 100%;
  height: 160px;
  object-fit: cover;
  cursor: pointer;
}

.product-info {
  padding: 10px;
}

.product-info h3 {
  margin: 0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.price {
  color: #ff4444;
  font-weight: bold;
  margin: 8px 0;
  font-size: 14px;
}

.product-actions {
  display: flex;
  gap: 8px;
}

.product-actions .el-button {
  flex: 1;
  padding: 6px 8px;
  font-size: 12px;
}

:deep(.el-dialog__body) {
  padding: 0;
  max-height: 70vh;
  overflow-y: auto;
}

:deep(.el-dialog__body::-webkit-scrollbar) {
  width: 6px;
}

:deep(.el-dialog__body::-webkit-scrollbar-thumb) {
  background-color: #ddd;
  border-radius: 3px;
}

:deep(.el-dialog__header) {
  padding: 15px;
  margin-right: 0;
  border-bottom: 1px solid #eee;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
}
</style> 